<style lang="scss" scoped>
.page-wrap {
  width: 750rpx;
  min-height: 100vh;
  background-color: #FFFFFF;

  &__item {
    width: 700rpx;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &-img {
      width: 100rpx;
      height: 100rpx;
      overflow: hidden;
      border-radius: 50%;
    }
  }

  &__btn {
    width: 690rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 10rpx;
    color: #fff;
    background-color: $fun-red-color;
    margin: 40rpx auto;

  }

  .h160 {
    height: 160rpx !important;
  }

  .h100 {
    height: 100rpx !important;
  }

}

.cell {
  &-item {
    height: 80rpx;
    background-color: #fafafa;
    box-sizing: border-box;
    padding-left: 30rpx;
    line-height: 80rpx;

    &__input {
      height: 80rpx;
      line-height: 80rpx;
    }
  }
}

.captcha-btn {
  padding: 0 20rpx;
  border-radius: 10rpx;
  background: $fun-border-color;
  height: 70rpx;
  line-height: 70rpx;
  margin-left: 30rpx;
  font-size: 28rpx;

  &.active {
    background: $fun-primary-color;
  }
}
</style>
<template>
  <div class="page-wrap">
    <view class="page-wrap__item bor-b h160" @click="changeHeadimg">
      <view class="fz-15 c9">
        头像
      </view>
      <view class="flex flex-vertical-c">
        <image :src="userInfo.headimg" class="page-wrap__item-img"></image>
        <layout-icon class="m-l-10" type="iconright" color="#666666" size="16"></layout-icon>
      </view>
    </view>
    <view class="page-wrap__item bor-b h100" @click="openPopName">
      <view class="fz-15 c9">
        昵称
      </view>
      <view class="flex flex-vertical-c c3 fz-15">
        {{ userInfo.nickname }}

      </view>
    </view>
    <view class="page-wrap__item bor-b h100">
      <view class="fz-15 c9">
        性别
      </view>

      <radio-group @change="radioChange" class="flex flex-vertical-c c3 fz-15">
        <label class="flex flex-vertical-c">
          <radio value="1" :checked="userInfo.sex==1"/>
          男
        </label>
        <label class="m-l-20 flex flex-vertical-c">
          <radio value="2" :checked="userInfo.sex==2"/>
          女
        </label>
      </radio-group>

    </view>

    <view class="page-wrap__item bor-b h100">
      <view class="fz-15 c9">
        生日
      </view>
      <picker class="c3 fz-15 flex1 flex flex-vertical-c flex-justify-r" mode="date" :value="userInfo.birthday"
              @change="bindDateChange">
        <text v-if="userInfo.birthday">
          {{ userInfo.birthday }}
        </text>
        <text v-else>
          选择生日
        </text>
        <layout-icon style="display: inline-block;" class="m-l-10" type="iconright" color="#666666"
                     size="16"></layout-icon>
      </picker>

    </view>

    <view class="page-wrap__item bor-b h100" @click="realFn">
      <view class="fz-15 c9">
        实名认证
      </view>
      <view class="flex flex-vertical-c c3 fz-15">
        {{ userInfo.idcard ? userInfo.idcard : '去实名认证' }}
        <layout-icon class="m-l-10" type="iconright" color="#666666" size="16"></layout-icon>
      </view>
    </view>
    <!--    <view class="h10 w-full " style="background-color: #f7f7f7;"></view> -->
    <view class="page-wrap__item bor-b h100" @click="openBindPhonePopup">
      <view class="fz-15 c9">
        手机号
      </view>
      <view class="flex flex-vertical-c c3 fz-15">
        {{ userInfo.phone }}
        <layout-icon class="m-l-10" type="iconright" color="#666666" size="16"></layout-icon>
      </view>
    </view>
    <view class="page-wrap__item bor-b h100" @click="$linkTo('/pages/address/list')">
      <view class="fz-15 c9">
        收货地址
      </view>
      <view class="flex flex-vertical-c c3 fz-15">
        <layout-icon class="m-l-10" type="iconright" color="#666666" size="16"></layout-icon>
      </view>
    </view>

    <view @click="logoutFn" class="page-wrap__btn  fz-15 c3 text-center">
      退出
    </view>

    <layout-popup ref="bindPhone">
      <view class="w-full border-box p-l-15 p-r-15 p-b-15">
        <view class="flex flex-vertical-c flex-justify-between h45">
          <view class="fz-17 c3">
            绑定手机号
          </view>
          <view class="fz-14 c9" @click="closeBindPhonePopup">
            取消绑定
          </view>
        </view>
        <div class="m-b-10 flex flex-vertical-c">
          <view class="cell-item flex1">
            <input class="cell-item__input" type="number" @input="inputBindPhone"/>
          </view>
          <div class="captcha-btn" :class="{active:checkPhoneDone}" @click="sendCaptchaByBind">
            <span class="text" v-if="!bindcaptchaSend">获取验证码</span><span class="text active" v-else>{{ binds }}s</span>
          </div>
        </div>
        <view class="cell-item m-b-10">
          <input class="cell-item__input" type="number" @input="inputBindCaptcha"/>
        </view>
        <view @click="bindPhoneFn" class="w-full h50 lh50 text-center fz-15 c3 primary-bg"
              :class="{active:bindcaptcha}">
          绑定手机号
        </view>

      </view>

    </layout-popup>

    <layout-popup ref="bindName">
      <view class="w-full border-box p-l-15 p-r-15 p-b-15">
        <view class="flex flex-vertical-c flex-justify-between h45">
          修改昵称
        </view>
        <view class="cell-item m-b-10">
          <input class="cell-item__input" type="text" v-model="nickName"/>
        </view>
        <view @click="bindNickName" class="w-full h50 lh50 text-center fz-15 c3 primary-bg">
          确定
        </view>

      </view>

    </layout-popup>

    <layout-popup ref="realName">
      <view class="w-full border-box">
        <view class="flex flex-vertical-c flex-justify-between h45 border-box p-l-15 p-r-15">
          <view class="fz-17 c3">
            实名认证
          </view>
          <!--          <view class="fz-14 c9" v-if="userInfo.real_name" >
                      取消身份认证
                    </view> -->
          <view></view>
        </view>
        <input class="cell-item m-b-10 border-box p-l-15 p-r-15" placeholder="请输入真实姓名" v-model="real_name"/>

        <input class="cell-item m-b-10 border-box p-l-15 p-r-15" placeholder="请输入身份证号" v-model="idcard"/>
        <view v-if="userInfo.real_name" class="w-full h50 lh50 text-center fz-15 c9" @click="$closePop('realName')">
          取消
        </view>
        <view v-else @click="sureReal" class="w-full h50 lh50 text-center fz-15 c9 bg-color-primary">
          确定
        </view>

      </view>

    </layout-popup>

  </div>

</template>

<script>

import LayoutIcon from '@/components/layout-icon/layout-icon'
import LayoutPopup from '@/components/layout-popup/layout-popup.vue'
import { pageMixin } from '@/mixins'
import { bindPhone, changeHeadimg, changeNickname, changeUserInfo, getUserInfo, logout, sendSms } from '@/api/user'
import { backFunc, error, hideLoading, linkToEasy, showLoading, toast } from '@/common/fun'
import { chooseImageByPromise, emptyObject, uploadImages } from '@/common/helper'
import Storage from '@/common/Storage'
import { mapActions } from 'vuex'
import { regPhone } from '@/common/Regs'
import { Exception } from '@/common/Exception'

let setintervalInstanceByBind = null
export default {
  mixins: [pageMixin],
  components: {
    LayoutIcon,
    LayoutPopup
  },
  data () {
    return {
      idcard: '',
      real_name: '',
      nickName: '',
      userInfo: {
        id: '',
        phone: ''
      },
      require_back: 0,
      checkPhoneDone: false,
      bindphone: '',
      bindcaptcha: '',
      binds: 60,
      bindsmsid: null,
      bindcaptchaSend: false
    }
  },
  methods: {
    async changeHeadimg () {
      const { path, size } = await chooseImageByPromise().then(res => res[0]).catch(err => {
        throw Error(err.errMsg)
      })

      // if (size > 1024 * 10) {
      //   error('请上传小于2M的照片')
      //   return
      // }
      showLoading('上传中')
      const oss_url = await uploadImages({ imgs: [path] }).then(res => res[0]).catch(err => {
        hideLoading()
        throw err
      })
      changeHeadimg({ headimg: oss_url }).then(res => {
        this.refresh_user_info()
        hideLoading()
      }).catch(err => {
        hideLoading()
        error(err.msg || '修改头像失败')
      })
    },
    async sureReal () {
      if (!this.real_name) {
        error('请填写真实姓名')
        return
      }
      if (!this.idcard) {
        error('请填写身份证号')
        return
      }
      await changeUserInfo({
        filed: 'idcard',
        value: this.idcard
      }).then(res => {
        changeUserInfo({
          filed: 'real_name',
          value: this.real_name
        }).then(res => {
          toast('修改成功')
          this.$closePop('realName')
          this.refresh_user_info()
        }).catch(err => {
          this.refresh_user_info()
          Exception.handle(e)
          this.$closePop('realName')
        })
      }).catch(err => {
        this.$closePop('realName')
        this.refresh_user_info()
        Exception.handle(e)
      })
    },
    realFn () {
      this.$openPop('realName')
      this.real_name = this.userInfo.real_name
      this.idcard = this.userInfo.idcard
    },
    async bindDateChange (e) {
      const birthday = e.detail.value
      changeUserInfo({
        filed: 'birthday',
        value: birthday
      }).then(res => {
        toast('修改成功')
        this.refresh_user_info()
      }).catch(err => {
        this.refresh_user_info()
        Exception.handle(e)
      })
    },
    async bindNickName () {
      if (!this.nickName) {
        error('请填写昵称')
        return
      }
      if (this.nickName == this.userInfo.nickname) {
        toast('修改成功')
        this.$closePop('bindName')
      } else {
        await changeNickname({ nickname: this.nickName }).then(res => {
          toast('修改成功')
          this.$closePop('bindName')
          this.refresh_user_info()
        }).catch(err => {
          this.$closePop('bindName')
          Exception.handle(err)
        })
      }
    },
    openPopName () {
      this.nickName = this.userInfo.nickname
      this.$openPop('bindName')
    },
    radioChange (e) {
      const boo = e.detail.value
      changeUserInfo({
        filed: 'sex',
        value: boo
      }).then(res => {
        toast('修改成功')
        this.refresh_user_info()
      }).catch(err => {
        this.refresh_user_info()
        Exception.handle(e)
      })
    },
    restBindPhoneFrom () {
      this.checkPhoneDone = false
      this.bindphone = ''
      this.bindcaptcha = ''
      this.binds = 60
      this.bindsmsid = null
      this.bindcaptchaSend = false
    },
    sendCaptchaByBind () {
      if (!this.bindphone) {
        error('发送验证码失败')
        return
      }
      sendSms({
        phone: this.bindphone,
        type: 'bingphone'
      }).then(res => {
        if (res.data) {
          this.bindsmsid = res.data
          this.bindcaptchaSend = true
          this.binds = 60
          setintervalInstanceByBind = setInterval(this.minusFnByBind, 1000)
        }
      }).catch(err => {
        Exception.handle(err)
      })
    },
    minusFnByBind () {
      if (this.binds > 1) {
        this.binds--
        return
      }
      clearInterval(setintervalInstanceByBind)
      this.bindcaptchaSend = false
    },
    async bindPhoneFn () {
      try {
        showLoading()
        const postData = {
          phone: this.bindphone,
          captcha: this.bindcaptcha,
          BizId: this.bindsmsid
        }
        if (!emptyObject({
          obj: postData,
          strice: 1
        })) {
          throw Error('手机号码或者验证码为空')
        }
        await bindPhone(postData).then().catch(err => {
          throw err
        })
        hideLoading()

        this.restBindPhoneFrom()

        const newUserInfo = {
          ...this.userInfo,
          phone: this.bindphone
        }
        this.userInfo = newUserInfo
        this.setUserInfo(newUserInfo)

        this.closeBindPhonePopup()

        if (this.require_back) {
          backFunc()
          return
        }
        toast('绑定成功')
      } catch (e) {
        hideLoading()
        Exception.handle(e)
      }
    },
    inputBindCaptcha (e) {
      this.bindcaptcha = e.target.value
    },
    inputBindPhone (e) {
      this.bindphone = e.target.value
      this.checkPhoneDone = regPhone.test(this.bindphone)
    },
    async logoutFn () {
      var _self = this
      uni.showModal({
        title: '提示',
        content: '是否退出登录',
        success: res => {
          if (res.confirm) {
            logout({}, { tip: 'loading' }).then(res => {
              _self.setUserInfo({})
              Storage.remove('access_token')
              linkToEasy('/pages/home')
            }).catch(() => {
            })
          }
        }
      })
    },
    openBindPhonePopup () {
      this.$openPop('bindPhone')
    },
    closeBindPhonePopup () {
      this.$closePop('bindPhone')
    },
    refresh_user_info () {
      // 刷新信息
      // showLoading('刷新信息')
      getUserInfo().then(res => {
        console.log(res)
        this.userInfo = res.data
        // hideLoading()
      }).catch(e => {
        // hideLoading()
      })
    },
    ...mapActions({
      setUserInfo: 'user/setUserInfo'
    })

  },
  onLoad (options) {
    this.require_back = options.require_back ? 1 : 0
    this.refresh_user_info()
  }

}

</script>
